
import turtle
import random


def goto(p):
    turtle.up()
    turtle.goto(p)
    turtle.down()

def make_dot():
    x=random.randint(-300,300)
    y=random.randint(-300,300)
    return [x, y]
make_dot()
# 贪吃蛇
pos=[[30,0],[60,0],[90,0]]

num = 0
def draw():
    global num
    turtle.clear()
    if num==10:
        food.append(make_dot())
        num = 0
    num+=1
    for i in food:
        goto(i)
        turtle.dot(30, 'gold')

    for i in range(len(pos)):
        goto(pos[i])
        turtle.dot(30, 'red')
        if i+1 == len(pos):
            turtle.dot(5, 'gold')
    move()
    touch()
    turtle.ontimer(draw, 200)
def move():
    global is_delete
    if is_delete:
        pos.pop(0)
    else:
        is_delete = True
    if turtle.heading() == 90:
        pos.append([pos[-1][0], pos[-1][1]+30])
    if turtle.heading() == 180:
        pos.append([pos[-1][0] - 30, pos[-1][1]])
    if turtle.heading() == 0:
        pos.append([pos[-1][0] +30, pos[-1][1]])
    if turtle.heading() == 270:
        pos.append([pos[-1][0], pos[-1][1]-30])

def touch():
    """
    蛇跟小球进行接触
    """
    global is_delete
    snake_head = pos[-1]
    for i in food:
        if (snake_head[0]-15 > i[0]-15 and snake_head[0]-15< i[0]+15 \
            and snake_head[1] > i[1]-20 and snake_head[1]<i[1]+20) or \
                (snake_head[0]+15 > i[0]-15 and snake_head[0]+15< i[0]+15 \
            and snake_head[1] > i[1]-20 and snake_head[1]<i[1]+20):
            food.remove(i)
            is_delete = False
            break


def up():
    turtle.seth(90)

def left():
    turtle.seth(180)
def right():
    turtle.seth(0)
def down():
    turtle.seth(270)
food = [make_dot()]
is_delete = True
draw()
turtle.onkeypress(up,'Up')
turtle.onkeypress(left,'Left')
turtle.onkeypress(right,'Right')
turtle.onkeypress(down,'Down')
turtle.listen()
turtle.tracer(False)

turtle.done()